import json
import random
from flask import Blueprint, request, jsonify
from application.models.users.user import *
from application.tools.myredis import r
course_blue = Blueprint("courseblue", __name__)
# 添加课程使用， 获取标签， 分类， 类别
@course_blue.route("/getTags")
def getTags():
    # 获取标签
    tags = Tags.query.all()
    tagslist = [{"id": i.id,"name": i.name}for i in tags]
    # 获取分类
    types = Ctype.query.all()
    typeslist = [{"id": i.id, "name": i.name}for i in types]
    # 获取类别
    ctype = CourseType.query.all()
    ctypelist = [{"id": i.id, "name": i.name}for i in ctype]
    # 返回数据
    return jsonify({"code": 200, "tags": tagslist, "types": typeslist, "clist": ctypelist})

# 七牛云
@course_blue.route("/get_qntoken")
def get_qntoken():
    # -*- coding: utf-8 -*-
    # flake8: noqa
    from qiniu import Auth
    # 需要填写你的 Access Key 和 Secret Key
    access_key = 'NZ5RXgUXBp4w5-Wa0E9f9bnhpvSNgk72ff0QhGnz'
    secret_key = 'zlS8Y7HwNIzBfjoMa__ysbr4-JjzrvoXPnDqeLA3'
    # 构建鉴权对象
    q = Auth(access_key, secret_key)
    # 要上传的空间
    bucket_name = 'h2205a-ljy'
    # 3600为token过期时间，秒为单位。3600等于一小时
    token = q.upload_token(bucket_name)
    return jsonify({"code": 200, "token": token})

# 添加课程
@course_blue.route('/addCourse', methods=['POST'])
def addCourse():
    try:
        # 获取参数
        data = json.loads(request.data)
        # 校验参数是否获取
        if not data:
            return jsonify({"code": 400, "msg": "缺少参数"})
        # 写入课程表
        course = Course(name=data.get('name'), url=data.get('url'), descrip=data.get('desc'), ctype=data.get("type"))
        db.session.add(course)
        # 获取新加的课程id
        scourse = Course.query.filter(Course.name == data['name']).first()

        # 写入课程标签
        for i in data['tags']:
            tag = Tags.query.filter(Tags.id==i).first()
            scourse.tags.append(tag)
            # sql = "insert into course_tag(courseid,tagid) values(%d,%d)"%(scourse.id, int(i))
            # db.session.execute(sql)

        # 课程分类表
        for i in data['ctype']:
            sql = "insert into course_cate(courseid,course_typeid) values(%d,%d)"%(scourse.id, int(i))
            db.session.execute(sql)
        db.session.commit()
        return jsonify({"code": 200, "msg": "添加成功"})
    except:
        db.session.rollback()
        return jsonify({"code": 400, "msg": "添加失败"})

import math
# @user_blue.route("/getCourse")
# def getCourse():
#     # 获取参数page
#     page = request.args.get("page")
#     # 获取已上线， 即将上线条件
#     online = int(request.args.get('is_publish'))
#     # 查询总条数
#     total = Course.query.filter(Course.is_publish == online).count()
#     # 定义每页显示多少条
#     page_size = 3
#     # 查询当前页记录
#     start = math.ceil((int(page)-1)*page_size)
#     # 获取排序字段
#     orderpara = request.args.get('orderpara')
#     print("orderpata=====", orderpara)
#     if orderpara == "new":
#         course = Course.query.order_by(Course.create_time.desc()).filter(Course.is_publish == online).offset(start).limit(page_size).all()
#     else:
#         course = Course.query.order_by(Course.views.desc()).filter(Course.is_publish == online).offset(start).limit(page_size).all()
#
#     # 获取过来的数据必须序列化
#     list = [{"id": i.id, "name": i.name, "url": i.url, "views": i.views} for i in course]
#     # 返回结果
#     return jsonify({"code": 200, "clist": list, "total": total, "page_size": page_size})




# # flask期末作业
# @user_blue.route("/student")
# def student():
#     # 获取参数page
#     page = request.args.get("page")
#     # 查询总条数
#     total = Student.query.count()
#     # 定义每页显示多少条
#     page_size = 2
#     # 查询当前页记录
#     start = math.ceil((int(page)-1)*page_size)
#     # 分页获取的数据
#     student = Student.query.offset(start).limit(page_size).all()
#     # 获取过来的数据必须序列化
#     list = [{"id": i.id, "name": i.name, "number": i.number} for i in student]
#     # 返回结果
#     return jsonify({"code": 200, "clist": list, "total": total, "page_size": page_size})

[
        {
            "course_id": 1,
            "id": 1,
            "msg": "第一条评论",
            # "reply_id": null,
            "son": [
                {
                    "course_id": 1,
                    "id": 6,
                    "msg": "第一条的评论的评论",
                    "reply_id": 1,
                    "son": [
                        {
                            "course_id": 1,
                            "id": 7,
                            "msg": "第一条评论的评论的评论",
                            "reply_id": 6,
                            "user": 1
                        }
                    ],
                    "user": 18
                }
            ],
            "user": 1
        },
        {
            "course_id": 1,
            "id": 5,
            "msg": "d第二条",
            # "reply_id": null,
            "user": 18
        }
    ]
@course_blue.route('/getCourse', methods=['GET'])
def getCourse():
    # 获取当前页面
    page = request.args.get("page")
    # 获取已上线， 即将上线条件
    online = int(request.args.get('is_publish'))

    # 定义每页显示多少条
    page_size = 3
    # 获取条件
    start = math.ceil((int(page)-1)*page_size)
    # 获取类别
    types = int(request.args.get('types'))
    # 获取类别
    tags = int(request.args.get('tags'))
    # 排序字段
    orderpara = request.argas.get('orderpara')
    # 重构where条件
    where = " 1=1"
    if online:
        where = where + " and c.is_publish="+str(online)

    if types > 0:
        where = where + " and c.ctype="+str(types)

    # 排序
    orderby = " order by c.views desc"
    if orderpara == "new":
        orderby = " order by c.create_time desc"
    # 查询一共有多少条
    if tags > 0:
        countsql = "select count(c.id) as tcount from course as c inner join course_tag as ct on c.id=ct.courseid where ct.tagid=" + str(tags)+" and"+where
    else:
        countsql = "select count(c.id) as tcount from course as c where"+where
    cres = db.session.execute(countsql)
    cdata = cres.fetchone()
    # 查询总条数
    total = cdata["tcount"]
    # 查询当前页对象
    if tags > 0:
        sql = "select c.* from course as c inner join course_tag as ct on c.id=ct.courseid where ct.tagid=" + str(tags) + " and " + where + orderby + " limit " + str(start) + "," + str(page_size)
    else:
        sql = "select c.* from course as c where " + where+orderby+" limit "+str(start)+","+str(page_size)
    res = db.session.execute(sql)
    data = res.fetchall()
    # 获取过来的数据必须序列化
    clist = [{"id": i.id, "name": i.name, "url": i.url, "views": i.views} for i in data]
    # 返回结果
    return jsonify({"code": 200, "clist": clist, "total": total, "page_size": page_size})

# 课程详情页面
@course_blue.route('/courseDetail', methods=['GET'])
def courseDetail():
    # 获取参数id
    course_id = request.args.get("cid")
    userid = request.args.get("userid")
    # 查询课程
    # sql = "SELECT * from course WHERE id="+str(course_id)
    # data = db.session.execute(sql)
    # cou = data.fetchall()
    cou = Course.query.filter(Course.id == course_id).first()
    coudict = {"id": cou.id, "name": cou.name, "views": cou.views, "descrip": cou.descrip, "tcount": cou.tcount, "son": [], "ctype": cou.ctype}

    # 判断用户是否登录
    if userid:
        key = "user" + str(userid) + "good" + str(course_id)
        r.hash_add(key, "id", cou.id)
        r.hash_add(key, "name", "商品"+str(cou.name))
        r.hash_add(key, "url", cou.url)

    # 通过课程id查询课程
    sql = "SELECT * FROM jie  where courseid=%s order by tcount asc" % course_id
    res = db.session.execute(sql)
    course = res.fetchall()
    # 课程章节列表
    list = []
    for i in course:
        dict = {"id": i.id, "name": i.name, "tcount": i.tcount, "url": i.url}
        list.append(dict)
    coudict["son"] = list

    return jsonify({"code": 200, "cou": coudict})


# 浏览记录
@course_blue.route('/getDetail', methods=['GET'])
def getDetail():
    # 接收参数
    userid = request.args.get('userid')
    findkey = "user" + str(userid) + "*"
    gidlist = r.getvalues(findkey)
    reslist = []
    for i in gidlist:
        goods = r.getall_hash(i)
        dict = {}
        for k, v in goods.items():
            kk = k.decode()
            vv = v.decode()
            dict[kk] = vv
        reslist.append(dict)
    return jsonify({"code": 200, "reslist": reslist})




# 课程章节选择课程添加
@course_blue.route("/get_course", methods=['GET'])
def add_chapter():
    # 获取全部课程
    course = Course.query.all()
    # 课程章节列表
    list = []
    for i in course:
        dict = {"id": i.id, "name": i.name}
        list.append(dict)
    return jsonify({"code": 200, "list": list})

import os
# 保存图片到本地
@course_blue.route("/upload", methods=["POST"])
def upload():
    # 获取文件
    file = request.files.get('file')
    # 获取文件名
    filename = file.filename
    path = os.path.join("static/upload/media/"+filename)
    # 保存文件
    file.save(path)
    # 通过id获取到数据， url
    # 用url接收数据库中的url
    # remove加上数据库中的url就可以直接删除
    # 删除文件
    # os.remove(url)

    return jsonify({"code": 200, "url": path})

# 添加课程章节杰克
@course_blue.route("/addjie", methods=["POST"])
def addjie():
    # 获取参数
    data = json.loads(request.data)
    if not data:
        return jsonify({"code": 10010, "mes": "参数错误"})
    # 添加课程章节
    name = data['name']
    url = data['url']
    tcount = data['tcount']
    courseid = data['courseid']
    try:
        jie = Jie(name=name, url=url, tcount=tcount, courseid=courseid)
        db.session.add(jie)
        db.session.commit()
    except Exception as e:
        print(e)
        return jsonify({"code": 10010, "mes": "章节添加失败"})
    return jsonify({"code": 200, "mes": "章节添加成功"})
